
<template>
  <div class="project-request-container">
    <div class="form">
      <el-row>
        <el-col :xs="24" :sm="24" :lg="24" class="border"></el-col>
      </el-row>
      <el-row class="choose" v-if="canEdit">
      </el-row>
      <el-form ref="form" :model="form" :rules="rules" label-width="150px">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
             <span @click="showBaseInfo(false)" v-if="showBase" style="font-size:20px;cursor:pointer;" >基础信息<i class="el-icon-arrow-down el-icon--right"></i></span>
            <span @click="showBaseInfo(true)" v-if="!showBase" style="font-size:20px;cursor:pointer;">基础信息<i class="el-icon-arrow-up el-icon--right"></i></span>
          </div>
          <el-row v-if="showBase">
            <el-col :span="8">
              <div>
                <el-form-item label="项目名称" :required="true">
                  <el-input
                    v-model="form.project_name"
                    :disabled="mode != 'resourceCreate'"
                    placeholder="请输入项目名称"
                    :prefix-icon="projectIcon"
                    @change="handleProjectNameChanged"
                  ></el-input>
                </el-form-item>
                <el-form-item label="客户全称(原文)" :required="false">  
                  <el-autocomplete 
                    :disabled="!iscanEdit"  
                    class="inline-input"
                    v-model="form.customer_full_name"
                    placeholder="请输入客户全称或简称"
                  ></el-autocomplete>
                </el-form-item>
                <el-form-item label="所属事业部" :required="true">
                  <el-autocomplete
                    class="inline-input"
                    v-model="form.business_department"
                    :fetch-suggestions="querySearchDepartment"
                    placeholder="请输入事业部名或拼音"
                    :disabled="!iscanEdit"
                  ></el-autocomplete>
                </el-form-item>
                <el-form-item label="所属事业群">
                  <el-input v-model="form.business_group" readonly></el-input>
                </el-form-item>
              </div>
            </el-col>
            <el-col :span="8">
              <div>
                <el-form-item label="项目经理" :required="true">
                  <el-autocomplete
                    class="inline-input"
                    v-model="form.project_manager"
                    placeholder="请输入姓名或拼音"
                    :disabled="!iscanEdit"
                  >
                    <template slot-scope="{ item }">
                      <div class="name">{{ item.value }}_{{ item.ldap }}</div>
                    </template>
                  </el-autocomplete>
                </el-form-item>
                <el-form-item label="客户简称">
                  <el-input
                    v-model="form.customer_abrv_name"
                    :disabled="!iscanEdit"
                  ></el-input>
                </el-form-item>
                <el-form-item label="所属事业部负责人">
                  <el-input
                    v-model="form.business_department_manager"
                    readonly
                  ></el-input>
                </el-form-item>
                <el-form-item label="所属事业群负责人">
                  <el-input
                    v-model="form.business_group_manager"
                    readonly
                  ></el-input>
                </el-form-item>
              </div>
            </el-col>
            <el-col :span="8">
              <div>
                <el-form-item label="需求类型" :required="false">
                  <el-select
                      v-model="form.demand_type"
                      placeholder="选择需求类型"
                      style="width: 105px"
                      :disabled="!iscanEdit"
                    >
                      <el-option label="全体" value="全体"></el-option>
                      <el-option label="仅Offshore" value="仅Offshore"></el-option>
                      <el-option label="Offshore+ODC" value="Offshore+ODC"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="客户等级">
                  <el-col>
                    <el-input
                      v-model="form.customer_level"
                      :disabled="!iscanEdit"
                    ></el-input>
                  </el-col>
                </el-form-item>
                <el-form-item label="项目开始日期" :required="true">
                  <el-col>
                    <el-date-picker
                      type="date"
                      placeholder="选择日期"
                      value-format="yyyy-MM-dd"
                      v-model="form.project_start_date"
                      style="width: 100%;"
                      :disabled="!canEdit || !dateEdit || !iscanEdit"
                      @change="startchange($event)"
                    ></el-date-picker>
                  </el-col>
                </el-form-item>
                <el-form-item label="项目结束日期" :required="true">
                  <el-col>
                    <el-date-picker
                      @change="projectEndDateChanged"
                      type="date"
                      placeholder="选择日期"
                      value-format="yyyy-MM-dd"
                      v-model="form.project_end_date"
                      style="width: 100%;"
                      :disabled="!canEdit || !dateEdit || !iscanEdit"
                    ></el-date-picker>
                  </el-col>
                </el-form-item>
              </div>
            </el-col>
          </el-row>
        </el-card>
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>工数预测</span>
            <div class="tip">tip:双击任一月即可设定为项目起始月和结束月，可以批量填写工数</div>
          </div>
          <el-row>
            <el-col :xs="24" :sm="24" :lg="24" >
                <div style="float:right">
                    <el-button type="warning" class="btn-add" size="medium" icon="el-icon-plus" @click="addManPowerRow()">新增</el-button>
                    <el-button type="primary" plain class="btn-add" size="medium" @click="saveManPowerRow()">保存</el-button>
                    <el-button type="danger" slot="reference" plain class="btn-add" size="medium" @click="makeSureFn()">删除</el-button>
                    <!-- <el-button type="success" class="btn-add" size="medium"  @click="checkNewform()">更新日志</el-button> -->
                </div>
                <el-table
                    :data="manPowerList"
                    border
                    style="width: 100%"
                    id="tableMan"
                    max-height = '500'
                    v-loading="loadingManPowerMon"
                    @selection-change="handleSelectionChange"
                    :key="Math.random()"
                    show-summary
                    :summary-method="getSummaries"
                    :cell-class-name='getCellIndex'
                    :row-class-name="tableRowIndex"
                    :cell-style="tableCellStyle"
                    @cell-dblclick="selectCell">
                    <el-table-column
                    type="selection"
                    width="55">
                    </el-table-column>
                    <el-table-column
                    align="center"
                    :key="v.field"
                    v-for="v in manPowerColumns"
                    :prop="v.field"
                    :fixed="v.fixed"
                    :label="v.title"
                    :width="v.width?v.width:''"
                    :min-width="v.min?v.min:''"
                    >
                    <template slot-scope="scope">
                        <span v-if="v.field == 'id'">{{ scope.$index + 1 }}</span>
                        <el-select
                        v-if="v.field == 'dept_id'"
                        size="mini"
                        v-model="scope.row[v.field]"
                        filterable
                        placeholder="请选择"
                        clearable
                        >
                        <el-option
                            v-for="item in departmentsFilter"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id"
                        >
                        </el-option>
                        </el-select>
                        <div  v-if="v.field == 'technical_field_ids'"   >
                        <el-cascader
                        v-model="scope.row[v.field]"
                        size="mini"
                        :options="techRangeFilter"
                        :props="{ checkStrictly: true }"
                        clearable ></el-cascader>
                        </div>
                        <span v-if="v.field == 'man_month' && scope.row.need_total_person_months" >{{scope.row.need_total_person_months.toFixed(2) }}</span>
                    </template>
                    </el-table-column>
                    <el-table-column v-for="(key,index) in estLabourMonth()" :key="index + key +'A'" :label="key+'月（人月）'" align="center" type="cell" :prop="key" min-width=150>
                        <template slot-scope="scope">
                            <!-- <div v-if="new Date().getFullYear()==key.substr(0,4)"> -->
                                <el-input
                                v-if="scope.row.month_display_need[key]"
                                size="mini"
                                placeholder="最多可填写两位小数"
                                v-model="scope.row.month_display_need[key].need_month"
                                oninput="value=value.replace(/^0[0-9]|[^\d.]/g,'').replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3')"
                                @input="calculateTotalManMonth($event)"
                                >
                                </el-input>
                                <el-input
                                v-else 
                                size="mini"
                                placeholder="最多可填写两位小数"
                                v-model="scope.row.month_display_need[key].need_month"
                                oninput="value=value.replace(/^0[0-9]|[^\d.]/g,'').replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3')"
                                @input="calculateTotalManMonth($event)"
                                >
                                </el-input>
                                <div style="font-size: 12px;" v-if="scope.row.month_display_need[key] && workData[key]" >
                                    折算人天：{{((Number(scope.row.month_display_need[key].need_month || 0) * Number(workData[key] ? workData[key].count : 0) )) | rounding}}</div> 
                                <div v-else>
                                     折算人天：{{ 0 }}
                                </div>
                            <!-- </div> -->
                        </template>
                    </el-table-column>
                </el-table>
                    <!-- <div style="color:red;float:right">tip：盘点时间截至本年度人月</div> -->
            </el-col>
          </el-row>
        </el-card>
      </el-form>
    </div>
    
    <el-dialog
      title="提示"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose">
      <span>确定删除该工时吗？</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelSureFn()">取 消</el-button>
        <el-button type="primary" @click="checkSure()">确 定</el-button>
      </span>
    </el-dialog>


    <el-dialog title="更新日志" :visible.sync="checkVisible" width="60%">
      <CheckNewdata v-if="checkVisible" :projectName = "projectName" ></CheckNewdata>
    </el-dialog>
    <el-dialog title="温馨提示" :visible.sync="checkSureVisible" width="50%" :before-close="handleClose">
        <el-alert
            v-if="showSuccsee"
            title="未盘点工时删除成功"
            type="success"
            :closable="false"
            style="margin-bottom:5px">
        </el-alert>
        <el-alert
            title="以下需求已投入人员："
            type="warning"
            :closable="false"
            style="margin-bottom:5px">
        </el-alert>
            <template>
                <div v-for="(key,index) in noSitePowers" :key="key+index">
                    {{key}}
                </div>
            </template>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelFn">取 消</el-button>
        <el-button type="primary" @click="deleteManPowerRow()">强制删除</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import pinyin from "pinyin";
import http from "@/views/sys/axios";
import { getHeaderName } from '@/app.config'
import checkNewdata from '../components/checkNewdata.vue'
export default {
  inject: ['reload'],
  name: "ProjectRequest",
  components: {
    CheckNewdata: checkNewdata
  },
  props: {
    formData: Object,
    mode: String
  },
  data() {
    return {
        addSign:false,
        changeIndex:1,
        dialogVisible:false,
        showSuccsee:false,
        valNum:0,
        tableDataIds:[],
        noSitePowersIds:[],
        noSitePowers:[],
        gethttp:true,
        needDay:'',
        workData:{},
        projectName:'',
        checkVisible:false,
        showBase:false,
        showStartData:'',
        showEndData:'',
        showData : [],
        showWeek: true,
        iscanEdit:false,
        startData:'',
        endData:'',
        monthArr:[],
        nowResult:[],
        startArr:[],
        endArr:[],
        showArr:'',
        tableHeight:500,
        manLdap:'',
        tabName:'0',
        columnId:'',
        totalManMonth1:0,
        avgCostRMB1: 0,
        form: {},
        form_id: '',
        newId: '',
        base_form: {},
        canEdit: this.mode === "resourceCreate" || this.mode === "resourceEdit",
        loading: false,
        loadingManPower: false,
        loadingManPowerMon: false,
        btnLoadingW:false,
        btnLoadingM:false,
        loadingFeishu: false,
        upload_api:
            process.env.VUE_APP_SOURSE_MANAGE_HOST +
            "/api/base/workflow/upload_attachment",
        username: "",
        projectIcon: "el-icon-more",
        project_name_save: "",
        project_name_list: [],
        profit: 0,
        profit_rate: 0,
        state: "",
        timeout: null,
        totalManMonth: 0,
        avgCostRMB: 0,
        software_platforms: [],
        hardware_platforms: [],
        corporations: [],
        departments: [],
        roles: [],
        customers: [],
        selectedManPowerRow: null,
        activeIndex: "1",
        projectPeriod: 0,
        employees: [],
        exchangeRate: [
            {
            id: 12,
            currency_name: "林吉特",
            currency_code: "MYR",
            rate: 1.657,
            },
            {
            id: 11,
            currency_name: "卢比",
            currency_code: "INR",
            rate: 0.095,
            },
            {
            id: 10,
            currency_name: "韩币",
            currency_code: "KRW",
            rate: 0.006,
            },
            {
            id: 8,
            currency_name: "人民币",
            currency_code: "RMB",
            rate: 1.0,
            },
            {
            id: 7,
            currency_name: "欧元",
            currency_code: "EUR",
            rate: 7.787,
            },
            {
            id: 4,
            currency_name: "日元",
            currency_code: "JPY",
            rate: 0.065,
            },
            {
            id: 3,
            currency_name: "美元",
            currency_code: "USD",
            rate: 7.036,
            },
            {
            id: 1,
            currency_name: "新台币",
            currency_code: "NTD",
            rate: 0.235,
            },
        ],
        estCost: 0,
        estIncome: 0,
        estIncomeRaw: 0,
        rules: {},
        techRangeFilter: [],
        departmentsFilter: [],
        endWeek: '',
        startWeek: '',
        inpVal: '',
        selectWeekList: [],
        numShow: false,
        startCell: -1,
        startCell1: -1,
        endCell: -1,
        endCell1: -1,
        projectsList: [],
        activeName: '1',
        // 人力投入
        manPowerColumns: [
            {field: 'id', title: '#', width: 40 , fixed: 'left',},
            {
            field: 'dept_id',
            title: '实施部门',
            fixed: 'left',
            min: 140
            },
            {field: 'technical_field_ids', title: '技术领域', fixed: 'left', min: 160},
            {field: 'man_month', title: '工时(人月)', fixed: 'left', width: 100},
        ],
        manPowerList: [],
        hasAddModel: false,
        dateEdit: true,
        feishuVisible: false,
        feishuMember:'',
        feishuOptions: [],
        feishuId: '',
        row:'',
        column:'',
        color:false,
        selectC:[],
        sitePowerIds:[],
        checkSureVisible:false,
        add:false
        };
  },
  watch: {
    projectPeriod() {
      this.projectPeriodChanged();
    },
  },
  filters: {
    rounding (value) {
      if(value || value === 0) { //这个判断是为了防止数据为空，页面渲染为NAN
        return Number(value).toFixed(2)
      }
    },
    numFilter(value) {
      let tempVal = parseFloat(value || 0).toFixed(3);
      let realVal = tempVal.substring(0, tempVal.length - 1);
      return realVal;
    },
    num45Filter(amount, decimalCount = 1, decimal = ".", thousands = ",") {
      try {
        decimalCount = Math.abs(decimalCount);
        decimalCount = isNaN(decimalCount) ? 2 : decimalCount;
        const negativeSign = amount < 0 ? "-" : "";
        let tempVal = Math.pow(10, 2);
        let i = parseInt(
          (amount = Math.abs(
            Number(Math.round(amount * tempVal) / tempVal) || 0
          ).toFixed(decimalCount))
        ).toString();
        let j = i.length > 3 ? i.length % 3 : 0;
        return (
          negativeSign +
          (j ? i.substr(0, j) + thousands : "") +
          i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousands) +
          (decimalCount
            ? decimal +
              Math.abs(amount - i)
                .toFixed(decimalCount).slice(2)
            : "")
        );
      } catch (e) {
        console.log(e);
      }
    },
  },
  created() {
    this.form = Object.assign({},this.formData)
    this.getname();
    this.getTechRange()
    this.getDepartment()
  },
  mounted() {
    this.projectsList = this.loadProject();
    this.customers = this.loadCustomers();
    this.software_platforms = this.loadSoftwarePlatforms();
    this.hardware_platforms = this.loadHardwarePlatforms();
    this.roles = this.loadRoles();
    this.employees = this.loadEmployees();
    this.corporations = this.loadCorporations();
    if (this.canEdit) {
      this.project_name_save = this.form.project_name;
    }
    if (this.mode != "resourceCreate") {
      this.dateEdit = this.$route.params.type
      this.getProjectDetail(this.$route.params.id)
    } else {
      this.getNewId()
    }
    if(this.mode == "resourceEdit") {
      this.activeName = '2'
    }
    this.base_form = Object.assign({},this.form)
  }, 
  methods: {
    cancelSureFn(){
      this.dialogVisible = false
      this.sitePowerIds = []
      this.getManPowerList(this.$route.params.id)
    },
    makeSureFn(){
      if(this.sitePowerIds.length<1){
            this.$message.warning("请先选择项目")
        }else{
          if(this.add){
            this.saveManPowerRow()
          }
          setTimeout(() => {
            this.dialogVisible = true
        }, 500);
        }
    },
    cancelFn(){
      this.sitePowerIds = []
      this.checkSureVisible = false
      this.getManPowerList(this.$route.params.id)
    },
    deleteManPowerRow(){
        let deData = {}
        deData['status'] = 1
        deData['site_power_ids'] = Array.from(new Set(this.noSitePowersIds)) 
        this.$axios({
            url: process.env.VUE_APP_SOURSE_MANAGE_HOST+'/api/v1/car_project/delete_demand',
            method: "post",
            headers: getHeaderName(),
            data:deData
        }).then((res) => {
            if(res.data.code === 200){
                // this.checkSureVisible = false
                this.dialogVisible = false
                this.$message.success("删除成功")
                this.sitePowerIds = []
                this.getManPowerList(this.$route.params.id)
                this.checkSureVisible = false
            }else{
                this.$message.error("删除失败")
                this.dialogVisible = false
                this.sitePowerIds = []
                this.getManPowerList(this.$route.params.id)
                this.checkSureVisible = false
            }
        })
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
        done();
        })
        .catch(_ => {});
    },
    checkSure(){
      let data = {}
      data['site_power_ids'] = Array.from(new Set(this.sitePowerIds)) 
      data['status'] = 0
      this.$axios({
          url: process.env.VUE_APP_SOURSE_MANAGE_HOST+'/api/v1/car_project/delete_demand',
          method: "post",
          headers: getHeaderName(),
          data:data
      }).then((res) => {
          if(res.data.data.not_del_site_power_ids.length<1){
              this.$message.success("删除成功")
              this.dialogVisible = false
              this.sitePowerIds = []
              this.getManPowerList(this.$route.params.id)
          }else{
              this.noSitePowers = res.data.data.not_del_site_powers
              this.noSitePowersIds = res.data.data.not_del_site_power_ids
              res.data.data.del_site_powers.length >0 ? this.showSuccsee = true : this.showSuccsee = false
              this.dialogVisible = false
              this.checkSureVisible = true
              this.sitePowerIds = []
              this.getManPowerList(this.$route.params.id)
          }
      })
    },
    handleSelectionChange(val){
      this.sitePowerIds=[]
        val.map(key=>{
            this.sitePowerIds.push(key.id)
        })
    },
    getWorkdata(){
        this.$axios({
        url: process.env.VUE_APP_SOURSE_MANAGE_HOST+'/api/v1/car_project/get_month_work_days?month_range='+this.estLabourMonth(),
        method: "get",
        headers: getHeaderName(),
      }).then((res) => {
          this.workData = res.data.data.data
      })
    },
    checkNewform(){
      this.checkVisible = true
    },
    showBaseInfo(flag){
      this.showBase = flag
    },
    handleClick(tab, event) {
      this.tabName = tab.name
    },
    showFeishu(id) {
      this.feishuVisible = true
      this.feishuId = id
    },
    queryAllMember(query) {
      if (query !== '') {
        this.loadingFeishu = true;
        setTimeout(() => {
            this.loadingFeishu = false;
            this.$axios({
                url: process.env.VUE_APP_SOURSE_MANAGE_HOST + '/api/v1/employee/list?keywords=' + query,
                method: "get",
                headers: getHeaderName(),
            }).then(res => {
                this.feishuOptions = res.data.data
            })
        }, 200);
      } else {
          this.feishuOptions = [];
      }
    },
    submitFeishu() {
      if(this.feishuMember == '') {
        this.$message.error("通知人员不能为空");
        return false;
      }
      let localUrl = `http://${window.location.host}`
      let data = {
        'project_site_power_id': this.feishuId,
        'receive_ldap': this.feishuMember.join(),
        'card_link_url': localUrl
      }
      this.$axios({
        url: `${process.env.VUE_APP_SOURSE_MANAGE_HOST}/api/v1/project/demand/assign/remind`,
        method: "post",
        data: data,
        headers: getHeaderName(),
      }).then((res) => {
        if (res.data.code == 200) {
          this.$message.success(res.data.message);
          this.feishuVisible = false
          this.feishuId = ''
          this.feishuMember == ''
        } else {
          this.$message.error(res.data.message);
        }
      });
    },
    getNewId() {
      this.$axios({
        url:
          process.env.VUE_APP_SOURSE_MANAGE_HOST +
          "/api/v1/project/uuid",
        method: "get",
        headers: getHeaderName(),
      }).then((res) => {
        this.newId = res.data.data
      });
    },
    canEditProjectName() {
      if (this.mode === "resourceCreate") {
        return true;
      } else {
        return false;
      }
    },
    tableRowIndex ({row, rowIndex}) {
      //把每一行的索引放进row
      row.index = rowIndex;  //拿到的索引赋值给row的index,在这个表格中能拿到row的里面都会包含index
      return ''  //className(类名)
    },
    tableCellStyle (row) {
      if(this.selectC.includes(row.row) && this.selectC.includes(row.column) ){
        return 'background-color:#13ce66;'
      } 
      else {
        return 'background-color:#fff;'
      }
    },
    getCellIndex: function ({ row, column, rowIndex, columnIndex }) {
      row.index = rowIndex;
      column.index = columnIndex;
    },
    selectCell(row, column, cell, event) {
      let flag = false
      if(column.type=='cell'){
        this.row = row
        this.column = column
        this.selectC.push(this.row,this.column)
        if(this.selectC.length==4){
          if(this.selectC[0].index!=this.selectC[2].index){ // 判断是不是同行
            this.selectC.splice(0, 2) // 不是同行删除前一个选择的值
            flag = true
          }else{
            this.selectC
          }
        }
        this.selectC.length > 4 ? this.selectC = [] : this.selectC
      }
      if(column.type != 'cell') {
        return false
      }
      let index = row.index
      let colIndex = column.index
      let inputList = []
      for(let key in row.month_display_need) {
        inputList.push({
          key: key,
          value: row.month_display_need[key]
        })
      }
      inputList = this.compFn(inputList)
      let selectList = []
      if((this.startCell < 0 && this.endCell < 0) || (this.startCell >= 0 && this.endCell >= 0) || flag) {  // 判双击选择一个单元格
        if(flag){
          selectList = []
        }
        this.startCell = colIndex - 5
        this.endCell = -1
        inputList.map((v,i) => {
          if(i == colIndex - 5) {
            selectList.push({
              key: v.key,
              value: true
            })
          } else {
            selectList.push({
              key: v.key,
              value: false
            })
          }
        })
      } else {
        this.endCell = colIndex - 5
        let min = this.startCell <= this.endCell ? this.startCell : this.endCell
        let max = this.startCell <= this.endCell ? this.endCell : this.startCell
        let oldList = []
        inputList.map((v,i) => {
          oldList.push({
              key: v.key,
              value: false
            })
          if(i >= min && i <= max) {
            selectList.push({
              key: v.key,
              value: true
            })
          } else {
            selectList.push({
              key: v.key,
              value: false
            })
          }
        })
        this.numShow = true
        this.showData=[]
        selectList.map(val => {
          if(val.value == true) this.showData.push(val.key)
        })
        if(this.selectC.length == 4 ){
          this.open(oldList,index)
        }
      }
      row.selectList = selectList
    },
    //月份排序
    compFn(arr){
      arr.forEach(item=>{
        item.list=new Date(item.key).getTime()
      })
      arr.sort((a,b)=>{
          return a.list - b.list
      })
      return arr
    },
    //周排序
    compFnWeek(arr){
      arr.forEach(item=>{
        item.list=item.key.split('-')
        item.days=Number(item.list[0])*365+Number(item.list[1])*7
      })
      arr.sort((a,b)=>{
        return a.days -b.days
      })
    },
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      //循环处理所有列数据
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '总计';
          return;
        }
        //将每列的所有数据数字化处理成一个数组
        const values = data.map(item => {
          if(column.type == 'cell' && item.month_display_need[column.property]) {
              return Number(item.month_display_need[column.property].need_month)
          } else {
             return NaN
          }
        });
        //当前列的所有数据全是数字类型时
        if (!values.every(value => isNaN(value))) {
          //将当前列数据数组中的所有值，从左到右依次累加处理
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return (parseFloat(prev) + parseFloat(curr)).toFixed(2);
            } else {
              return parseFloat(prev).toFixed(2)
            }
          }, 0);
        } else {
          sums[index] = '';
        }
      });
      return sums;
    },
    open(selectList,index) {
      this.changeIndex = index
      this.$prompt('请输入工数'+'('+this.showData+')', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^\d+(?:\.\d{1,2})?$/,
        inputErrorMessage: '最多可填写两位小数'
      }).then(({ value }) => {
        this.addAllManWeek(value)
        this.startCell = -1
        this.endCell = -1
        this.selectC = []
        this.manPowerList[index].selectList = selectList
      }).catch(() => {
        this.startCell = -1
        this.endCell = -1
        this.selectC = []
        this.manPowerList[index].selectList = selectList
      });
    },
    addAllManWeek(value) {
      this.manPowerList.map((item,index) => {
      if(this.changeIndex==index){
        item.selectList.map((v,i) => {
            if(v.value) {
              this.showData.map(val=>{
                item.month_display_need[v.key].need_month = value
              })
            }
          })
      }
    })
  },
  manPowerDelete(row,index,id) {
    this.$axios({
      url: `${process.env.VUE_APP_SOURSE_MANAGE_HOST}/api/v1/project/demand/${row.id}`,
      method: "delete",
      headers: getHeaderName(),
    }).then((res) => {
      if (res.data.code == 200) {
        this.$message.success(res.data.message);
        this.reload()
      } else {
        this.$message.error(res.data.message);
      }
    });
  },
    loadLocalFormData() {
      let localForm = localStorage.getItem("form");
      let localCalculated = localStorage.getItem("calculated");
      let formData = JSON.parse(localForm);
      let calculatedData = JSON.parse(localCalculated);
      if (localForm === null) {
        this.loading = false;
      } else {
        for (const d in formData) {
          this.form[d] = formData[d];
        }
        this.estCost = calculatedData.est_cost;
        this.estIncome = calculatedData.est_income;
        this.estIncomeRaw = calculatedData.est_income_raw;
        this.profit = calculatedData.profit;
        this.profit_rate = calculatedData.profit_rate;
        this.totalManMonth = calculatedData.total_man_month;
        this.avgCostRMB = calculatedData.avg_cost_RMB;
        this.loading = false;
        this.$notify.success("已载入保存数据");
      }
    },
    init_reckon() {
      console.log("init_reckon");
    },
    getdataPro() {
      return http.get(`/api/account/user/info`);
    },
    async getname() {
      try {
        const data = await this.getdataPro();
        this.username = data.data;
      } catch (err) {
        throw err;
      }
    },
    getManPowerList(id,week_col) {
      this.loadingManPowerMon = true
      this.$axios({
        url: `${process.env.VUE_APP_SOURSE_MANAGE_HOST}/api/v1/car_project/${id}/demand`,
        method: "get",
        headers: getHeaderName(),
      }).then((res) => {
        this.manPowerList = res.data.data
        // estLabourMonth() 
        this.manPowerList.map((item,ind)=>{
          let arrAd = Object.keys(item.month_display_need)
          this.estLabourMonth().map(mon=>{
            if(!arrAd.includes(mon)){
              // item.month_display_need[mon] = 
              this.$set(item.month_display_need,mon,{"need_day":0,"need_month":0})

            }
          })
        })
        this.loadingManPowerMon = false
        setTimeout(() => {
            this.getWorkdata()
        }, 200);
      });
    },
    getProjectDetail(id) {
        this.$axios({
        url: process.env.VUE_APP_SOURSE_MANAGE_HOST +"/api/v1/project/" + id,
        method: "get",
        headers: getHeaderName(),
      }).then((res) => {
        this.projectName = res.data.data.form_data.project_name
        this.startData = res.data.data.form_data.project_start_date
        this.endData = res.data.data.form_data.project_end_date
         this.initStartMonth()
         this.initEndtMonth()
        for (const d in res.data.data.form_data) {
          this.form[d] = res.data.data.form_data[d];
        }
        this.form.status = res.data.data.status
        this.getManPowerList(id,res.data.data.week_col)
      });
      this.form_id = id;
    },
    getExistProjectDetail(id) {
      // load data in view mode
      this.$axios({
        url:
          process.env.VUE_APP_PROJECT_REQUEST_HOST +
          "/api/base/project/apply?id=" + id,
        method: "get",
      }).then((res) => {
        if(res.data.code == 200) {
          for (const d in res.data.data.form) {
            this.form[d] = res.data.data.form[d];
          }
        }
      });
      this.form_id = id
    },
    getTechRange() {
      this.$axios({
        url: process.env.VUE_APP_SOURSE_MANAGE_HOST + '/api/v1/filter/technical_field/tree',
        method: "get",
        headers: getHeaderName(),
      }).then(res => {
        this.techRangeFilter = res.data.data
      })
    },
    getDepartment() {
        this.$axios({
        url: process.env.VUE_APP_SOURSE_MANAGE_HOST + '/api/v1/department/list',
        method: "get",
        headers: getHeaderName(),
      }).then(res => {
        this.departmentsFilter = res.data.data;
      }).catch((error) => {
        console.log(error);
      });
    },
    formSave(key) {
      let flag = false
      let flag1 = false
      if(key) {
        if(this.form.project_name == '') {
          this.$message.error("项目名称不能为空");
          return false;
        }
        if(this.form.project_manager == '') {
          this.$message.error("项目经理不能为空");
          return false;
        }
        if(this.form.project_start_date == '') {
          this.$message.error("项目开始日期不能为空");
          return false;
        }
        if(this.form.project_end_date == '') {
          this.$message.error("项目结束日期不能为空");
          return false;
        }
        if(this.form.business_department == '') {
          this.$message.error("所属事业部不能为空");
          return false;
        }
        this.manPowerList.map((item,ind) => {
          flag = flag || item.editModel
        })
      }
      if (flag || flag1) {
        this.$message.error("您有未保存的工数预测信息");
        return false;
      } else {
        var form_data = Object.assign({}, this.form);
        var pro_id = ''
        if(this.mode == 'resourceCreate') {
          pro_id = this.newId
        } else {
          pro_id = this.form_id
        }
        var data = {
            dept: this.form.business_department,	//是	string	立项事业部
            //project_type: this.form.status,	//是	string	项目类型
            project_name: this.form.project_name,	//是	string	项目名
            project_manager: this.form.project_manager,	//否	string	项目经理
            demand_type: this.form.demand_type,
            customer: this.form.customer_full_name,
            creator_name: this.username,	//否	string	创建人姓名
            status: this.form.status,
            form_data: form_data,
            id: pro_id,
            project_manager_ldap: this.manLdap
        };
        if(this.mode == 'resourceCreate') {
          this.$axios({
            url: process.env.VUE_APP_SOURSE_MANAGE_HOST + "/api/v1/project",
            method: "post",
            headers: getHeaderName(),
            data: data,
          }).then((res) => {
            if (res.data.code == 200) {
              this.$message.success("提交成功");
              if(key) {
                this.$router.push({ name: 'resourceForecast' })
              } else {
                this.$router.push({ name: 'resourceEdit', params: { id: pro_id } })
              }
            } else {
              this.$message.error(res.data.message);
            }
          });
        } else {
          this.$axios({
            url: process.env.VUE_APP_SOURSE_MANAGE_HOST + "/api/v1/project/" + this.$route.params.id,
            method: "post",
            headers: getHeaderName(),
            data: data,
          }).then((res) => {
            if (res.data.code == 200) {
              this.$message.success(res.data.message);
              if(key) {
                this.$router.push({ name: 'resourceForecast' })
              } else {
                this.getManPowerList(pro_id)
              }
            } else {
              // this.$message.error(res.data.message);
            }
          });
        }
      }
    },
    formReset() {
      localStorage.clear();
      this.$router.go(0);
    },
    getCalculated() {
      return {
        profit_rate:
          ((this.estIncome * this.form.currency - this.estCost) * 100) /
          this.estIncome,
        est_income: this.estIncome,
        total_man_month: this.totalManMonth,
        est_cost: this.estCost,
        est_income_raw: this.estIncomeRaw,
        profit: this.estIncome * this.form.currency - this.estCost,
        avg_cost_RMB: this.avgCostRMB,
        avg_income_RMB: this.totalManMonth
          ? this.est_income / this.totalManMonth
          : "0",
        submitter: this.username,
      };
    },
    isUndefined(para) {
      return para === void 0;
    },
    projectPeriodChanged() {
      let projectIncome = this.form.projectIncome;
      for (const i in projectIncome) {
        projectIncome[i].input = new Array(this.estLabourWeek().length).fill(
          0
        );
      }
      this.form.projectIncome = projectIncome;
    },
    calculateTotalManMonth(e) {
      let totalManMonth = 0;
      let list = this.manPowerList
      var sum = 0
      list.map((item) => {
        if (!item.total) {
          sum += this.sumManMonth(item)
        }
      });
      return sum;
    },
    loadProject(){
      this.$axios({
        url: process.env.VUE_APP_SOURSE_MANAGE_HOST +
        "/api/v1/project/list",
        method: "get",
        headers: getHeaderName(),
      }).then(
        (response) =>
            (this.projectsList = response.data.data.map((x) => {
              x.pinyin = pinyin(x.name, {
                style: pinyin.STYLE_NORMAL,
              }).join("");
              x.type = x.type || "";
              x.value = x.name || "";
              return x;
            }))
      );
    },
    querySearchProject(queryString, cb) {
      let restaurants = this.projectsList;
      let results = queryString ? restaurants.filter(this.createFilter1(queryString)) : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter1(queryString) {
      return (restaurant) => {
        return (
          restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) ===
            0 ||
          restaurant.type.toLowerCase().indexOf(queryString.toLowerCase()) === 0 ||
          restaurant.pinyin.indexOf(queryString.toLowerCase()) === 0
        );
      };
    },
    querySearchCorporation(queryString, cb) {
      let corporations = this.corporations;
      let results = queryString
        ? corporations.filter(this.createFilterNameAndPinyin(queryString))
        : corporations;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    querySearchDepartment(queryString, cb) {
      let departments = [{}];
      this.$axios.get(`${process.env.VUE_APP_PROJECT_REQUEST_HOST}/api/base/department/`, {params: { format: 'json', search: queryString, level: 2 }
          })
          .then(response => {
              for (let i of response.data.data) {
                  i.value = i.name;
              }
              departments = response.data.data;
              cb(departments);
          })
          .catch(error => {
              console.log(error);
          });
    },
    createFilterName(queryString) {
      return (item) => {
        return (
          item.value.indexOf(queryString) >= 0 ||
          item.pinyin.indexOf(queryString.toLowerCase()) >= 0
        );
      };
    },
    createFilterNameAndPinyin(queryString) {
      return (item) => {
        return item.value.indexOf(queryString) === 0;
      };
    },
    createFilter(queryString) {
      return (customer) => {
        return (
          customer.value.toLowerCase().indexOf(queryString.toLowerCase()) ===
            0 ||
          customer.abbr_name
            .toLowerCase()
            .indexOf(queryString.toLowerCase()) === 0 ||
          customer.pinyin.indexOf(queryString.toLowerCase()) === 0
        );
      };
    },
    handleProjectNameChanged() {
      if (this.canEdit && this.project_name_save == this.form.project_name) {
        this.projectIcon = "el-icon-check";
      } else {
        this.$axios({
          url:process.env.VUE_APP_SOURSE_MANAGE_HOST +
              "/api/v1/project/check/name",
          method: "post",
          headers: getHeaderName(),
          data: {
            name: this.form.project_name
          }
        }).then((response) => {
          if (this.form.project_name === "") {
            this.projectIcon = "el-icon-more";
          } else if (response.data.data.exist === true) {
            this.$message.error("项目已存在，请使用其它项目名");
            this.form.project_name = "";
            this.projectIcon = "el-icon-close";
          } else {
            this.projectIcon = "el-icon-check";
          }
        });
      }
    },
    handleSelectCurrency(item) {
      this.exchangeRate.map((v) => {
        if (v.id == item) {
          this.form.currency = v.rate;
        }
      });
    },
    handleSelectSales(item) {
      this.form.sales_id = item.id;
    },
    handleSelectProjectDirector(item) {
      this.form.project_director_id = item.id;
    },
    handleSelectCorporation(item) {
      this.form.corporation_id = item.id;
    },
    selectProjectName(project) {
      this.$axios({
          url: process.env.VUE_APP_PROJECT_REQUEST_HOST +
          "/api/v1/project/details?project_name="+this.form.project_name,
          method: "get",
          headers: getHeaderName(),
        }).then((response) => {
          if (response.data.code == 200) {
            this.form.status = 1;
            this.form = response.data.data
          } else {
            this.form.status = 0;
          }
        });
    },
    handleSelectProjectName(project) {
        this.$axios({
          url: process.env.VUE_APP_SOURSE_MANAGE_HOST +
          "/api/v1/project/details?project_name="+this.form.project_name,
          method: "get",
          headers: getHeaderName(),
        }).then((response) => {
          if (response.data.code == 200) {
            if(project.type == 'history'){
              this.form = response.data.data
            }else{
              this.form = Object.assign({},this.base_form)
              this.form = Object.assign(this.form,response.data.data)
              this.projectEndDateChanged(response.data.data.project_end_date)
            }
          } else {
          }
        });
    },
    clearProjectName(){
      this.form = Object.assign({},this.base_form)
    },
    projectEndDateChanged(d) {
      if (this.form.project_start_date) {
        const end = new Date(d);
        var start = this.form.project_start_date;
        start = new Date(start.toString().replace(/-/g, "/"));
        const duration = end.getTime() - start.getTime();
        const monthDuration = duration / (24 * 60 * 60 * 30 * 1000);
        let projectPeriod = Math.floor(monthDuration * 10) / 10;
        this.projectPeriod = this.form.project_period = projectPeriod;
        let weekCol = this.estLabourWeek()
        let list = this.manPowerList
        list.map((item,index) => {
          let weekSave = {}
          weekCol.map((item1,index1) => {
            if(item.week_display_need[item1.weeks]) {
              weekSave[item1.weeks] = item.week_display_need[item1.weeks]
            } else {
              weekSave[item1.weeks] = '0'
            }
          })
          item.week_display_need = Object.assign({},weekSave)
          this.$set(this.manPowerList, index, item)
        })
      }
      // 结束月份
      this.endArr=[]
      let endTime =new Date(d)
      this.endArr.push(endTime.getFullYear())
      this.endArr.push(endTime.getMonth() + 1)
      this.endArr.push(endTime.getDate() )
      this.nowResult=this.estLabourMonth()
    },
    // 开始月份
    startchange(e){
      this.startArr=[]
      let startTime =new Date(e)
      this.startArr.push(startTime.getFullYear())
      this.startArr.push(startTime.getMonth() + 1)
      this.startArr.push(startTime.getDate() )
      this.nowResult=this.estLabourMonth()
    },
    estLabourMonth(){
      let result =[]
      if(this.startArr.length!=0 && this.endArr.length!=0){
        // 不同年
        if(this.endArr[0]>this.startArr[0]){
          // 跨度大于一年
          if(this.endArr[0]-this.startArr[0]>0){
            let years=this.endArr[0]-this.startArr[0]
            // 开始时间
            for(var i =this.startArr[1];i<=12;i++){
              result.push(this.startArr[0]+'-'+i)
            }
            // 中间时间
            if(years>1){
              for(var k = 1;k < years; k++){
                for(var o =1;o <= 12; o++){
                  result.push(Number(this.startArr[0]) + Number(k) +'-'+o)
                }
              }
            }
            // 结束时间
            for(var j=1;j<=this.endArr[1];j++){
              result.push(this.endArr[0]+'-'+j)
            }
          }
        }
        // 跨度在一年之内
        let p1 = ''
        if(this.endArr[0]==this.startArr[0]){
          for(var p=Number(this.startArr[1]);p<=Number(this.endArr[1]);p++){
            result.push(this.endArr[0]+'-'+p)
            p1 = p
          }
        }
      }
      return result
    },
    //页面初始化月份
    initStartMonth(){
      // this.nowResult=this.estLabourMonth()
      this.startArr=[]
      this.startArr = this.startData.split("-")
        this.startArr = this.startArr.map(function(val) {
          if (val[0] == "0") {
            return (val = val.slice(1));
          } else {
            return val;
          }
        });
      this.nowResult=this.estLabourMonth()
    },
    initEndtMonth(){
      this.endArr=[]
      this.endArr = this.endData.split('-')
      this.endArr = this.endArr.map(function(val) {
        if (val[0] == "0") {
          return (val = val.slice(1));
        } else {
          return val;
        }
      });
      this.nowResult=this.estLabourMonth()
    },
    estLabourWeek() {
      const weeks = []
      const weekCol = []
      const start = new Date(this.form.project_start_date); //起始日期
      const end = new Date(this.form.project_end_date); //结束日期
      let beginDate = new Date(start.getFullYear(), 0, 1); //起始日期年份的第一天
      let endnDate = new Date(end.getFullYear(), 0, 1); //结束日期年份的第一天
      let bd = beginDate.getDay() >= 4 ? (beginDate.getDay() - 7) : beginDate.getDay()
      let ed = endnDate.getDay() >= 4 ? (endnDate.getDay() - 7) : endnDate.getDay()
      let beginWeek = Math.ceil((parseInt((start - beginDate) / (24 * 60 * 60 * 1000)) + 1 + bd) / 7); //起始日期在当年的周数
      let endWeek = Math.ceil((parseInt((end - endnDate) / (24 * 60 * 60 * 1000)) + 1 + ed) / 7); //结束日期在当年的周数
      let startWeek = beginWeek
      let startYear = start.getFullYear()
      if(start.getFullYear() == end.getFullYear()) {
        if(startWeek == 0) {
          let dateb11 = new Date(startYear-1+'-01-01 00:00:00')
          let date11 = new Date(startYear+'-01-01 00:00:00')
          let date1231 = new Date(startYear-1+'-01-01 00:00:00')
          let beforeWeek = Math.ceil((parseInt((date11 - date1231) / (24 * 60 * 60 * 1000)) + 1 + (dateb11.getDay() >= 4 ? (dateb11.getDay() - 7) : dateb11.getDay())) / 7); //起始年份前一年最后一天在当年的周数
          weeks.push({
            weeks: startYear-1 + "-" + beforeWeek,
            show: this.weekToDate(startYear-1,beforeWeek,5)
          });
          weekCol.push(startYear-1 + "-" + beforeWeek)
          startWeek++;
        }
        while (startWeek <= endWeek) {
          let daten11 = new Date(end.getFullYear()+1+'-01-01 00:00:00')
          let nextWeek = Math.ceil((parseInt((new Date(end.getFullYear()+1, 0, 1) - endnDate) / (24 * 60 * 60 * 1000)) + 1 + ed) / 7) //结束年份最后一天在当前年份的周数
          let str,show
          if(startWeek == nextWeek && daten11.getDay() < 4) {
              str = start.getFullYear()+1 + "-1"
              show = this.weekToDate(start.getFullYear()+1,1,5)
          } else {
              str = start.getFullYear() + "-" + startWeek
              show = this.weekToDate(start.getFullYear(),startWeek,5)
          }
          weeks.push({
            weeks: str,
            show: show
          });
          weekCol.push(str)
          startWeek++;
        }
      } else {
        while (startYear <= end.getFullYear()) {
          let dayMS=24*60*60*1000
          let betDay = new Date(startYear+1+'-01-01 00:00:00').getTime() - new Date(startYear+'-01-01 00:00:00').getTime()
          let newD1 = new Date(startYear,0,1)
          let newD2 = new Date(startYear,11,31)
          let betWeek = betDay / dayMS  - (newD2.getDay()+1) - (7-newD1.getDay())
          let day = 0
          if(newD1.getDay() < 4 && newD1.getDay() > 0) {
              day += 1
          }
          if(newD2.getDay() >= 4 || newD2.getDay() == 0) {
              day += 1
          }
          day += (betWeek / 7)
          for(let i = 1; i<=day; i++) {
            if((startYear == start.getFullYear() && i >= startWeek) || (startYear > start.getFullYear() && startYear < end.getFullYear()) || (startYear == end.getFullYear() && i <= endWeek)) {
              let str = startYear + "-" + i
              let show = this.weekToDate(startYear,i,5)
              weeks.push({
                weeks: str,
                show: show
              });
              weekCol.push(str)
            }
          }
          startYear++
        }
      }
      this.form.weekCol = weekCol
      return weeks
    },
    weekToDate(year,week,day) {
      let betDay = new Date(year+1+'-01-01 00:00:00').getTime() - new Date(year+'-01-01 00:00:00').getTime()
      let newD1 = new Date(year,0,1)
      let newD2 = new Date(year,11,31)
      let dayMS=24*60*60*1000
      let firstDay=firstDay=(7-newD1.getDay())*dayMS
      let weekMS=0
      if(newD1.getDay() < 4) {
         weekMS=(week-2)*7*dayMS
      } else {
        weekMS=(week-1)*7*dayMS
      }
      let result=newD1.getTime()+firstDay+weekMS+day*dayMS
      newD1.setTime(result)
      return newD1.getFullYear() + "/" + (newD1.getMonth()+1) + "/" +newD1.getDate()
    },
    // 验证重复元素，有重复返回true；否则返回false
    isRepeat(arr) {
        var hash = {};
        for(var i in arr) {
            if(hash[arr[i]]) {
            return true;
            }
            // 不存在该元素，则赋值为true，可以赋任意值，相应的修改if判断条件即可
            hash[arr[i]] = true;
        }
        return false;
    },
    saveManPowerRow(){
        this.add = false
        let saveData = {}
        let arr = []
        // let a = false
        // let b = false
        let tempObj = {}
        let tempArr = []
        this.manPowerList.map(item=>{
            item['project_workflow_id'] = this.$route.params.id
            // if( item.technical_field_ids.length < 1 ){
            //   this.gethttp = false
            //   this.loadingManPowerMon = false
            //   // a = true
            //   return false
            // } 
            // if(!item.dept_id){
            //   this.gethttp = false
            //   this.loadingManPowerMon = false
            //   // b = true
            //   return false
            // }
            if(item.technical_field_ids.length >0 && item.dept_id){
              this.loadingManPowerMon = true
              this.gethttp = true
              item['technical_field_id'] = item.technical_field_ids[item.technical_field_ids.length-1]
              arr.push(item['technical_field_id'])
              // 判断技术领域、实施部门是否相同
              tempObj={
                'dept_id':item['dept_id'],
                'technical_field_id':item['technical_field_id']
              }
              tempArr.push(JSON.stringify(tempObj))
              item['month_range'] = this.estLabourMonth()
              item['project_name'] = this.form.project_name
              this.estLabourMonth().map(e=>{ //遍历key 获取时间月
                  if(item.month_display_need[e]){
                    let num = item.month_display_need[e].need_month * this.workData[e].count    
                    num=num.toString()
                    item['month_display_need'][e]['need_day'] =((Number(item.month_display_need[e].need_month) * Number(this.workData[e] ? this.workData[e].count : 0))).toFixed(2)
                  }else{
                    item['month_display_need'][e] = {}
                    item['month_display_need'][e]['need_day'] = 0
                    item['month_display_need'][e]['need_month'] = 0
                  }
                  if(!item['month_display_need'][e]['need_month']){
                    item['month_display_need'][e]['need_month'] = 0 
                  }
              }) 
            }
        })
         if(this.isRepeat(tempArr)){
             this.$message.warning("已有相同的实施部门和技术领域，请重新填写")
             this.loadingManPowerMon = false
             return false
         }
        //  if(a||b){
        //    this.$message.warning("请填写实施部门和技术领域")
        //  }
        if(this.gethttp){
            saveData = this.manPowerList
            this.$axios({
                url: `${process.env.VUE_APP_SOURSE_MANAGE_HOST}/api/v1/car_project/demand`,
                method: "post",
                headers: getHeaderName(),
                data:saveData
                }).then(res=>{
                    if(res.data.code === 200){
                      if(res.data.message.includes("保存失败")){
                        this.$message.error(res.data.message)
                        this.getManPowerList(this.$route.params.id)
                        this.loadingManPowerMon = false
                      }else{
                        this.$message.success(res.data.message)
                        this.getManPowerList(this.$route.params.id)
                        this.loadingManPowerMon = false
                      }
                        
                    }else{
                        this.$message.error(res.data.message)
                    }
            })
        }
    },
    getId(){
     return  this.$axios({
          url: `${process.env.VUE_APP_SOURSE_MANAGE_HOST}/api/v1/project/uuid`,
          method: "get",
          headers: getHeaderName(),
        })
    },
    async addManPowerRow() {
        this.add = true
        try{
            const data = await this.getId()
            this.columnId = data.data.data
            let months = {}
            this.estLabourMonth().map(e=>{ //遍历key 获取时间月
                months[e] = {}
                months[e]['need_month'] = 0
                months[e]['need_day'] = months[e]['need_month'] * this.workData[e].count
            }) 
            let j = {
            dept_id: null,
            id: this.columnId,
            role: '',
            technical_field_ids: '',
            technical_field_id: '',
            technical_field_names:[],
            month_display_need: months,
            man_month: 0,
            project_name:this.form.project_name
            };
            this.manPowerList.push(j);
        }catch(err){
            throw new Error(err)
        }
    },
    addIncomeDistributionRow(bu) {
      if (bu) {
        this.form.incomeDistribution = [];
      }
      let rowCount = this.form.incomeDistribution.length;
      let j = {
        id: rowCount + 1,
        implement_department: bu || "",
        type: bu ? "bu" : "",
        percentage: bu ? 25 : 0,
        income: 0,
      };
      this.form.incomeDistribution.push(j);
    },
    sumManMonth(row) {
      let sum = 0
      if(this.showWeek){
        for(let key in row.week_display_need){
          sum += parseFloat(row.week_display_need[key] || 0)
        }
      }else {
        for(let key in row.month_display_need){
          sum += parseFloat(row.month_display_need[key] || 0)
        }
      }
      
      return sum;
    },
    sumManMonthPerM(ind) {
      let list = this.manPowerList
      var sum = 0
      list.map((item) => {
        if (!item.total) {
          sum += parseFloat(item.week_display_need[ind] || 0)
        }
      });
      return sum;
    },
    loadCustomers() {
      this.$axios
        .get(process.env.VUE_APP_PROJECT_REQUEST_HOST + "/api/base/customer/?format=json")
        .then(
          (response) =>
            (this.customers = response.data.map((x) => {
              x.pinyin = pinyin(x.full_name, {
                style: pinyin.STYLE_NORMAL,
              }).join("");
              x.abbr_name = x.abbr_name || "";
              x.value = x.full_name;
              return x;
            }))
        );
    },
    loadProjectName() {
      this.$axios({
        url: process.env.VUE_APP_PROJECT_REQUEST_HOST + '/api/base/project',
        method: "get",
        params: {
          "page":this.tableCurrent,
          "per_page":this.tableSize,
          "ldap":this.ldap
        }
      }).then(res => {
        this.tableData = res.data.data
        this.tableTotal = res.data.total
      })
    },
    loadSoftwarePlatforms() {
      this.$axios
        .get(process.env.VUE_APP_PROJECT_REQUEST_HOST + "/api/base/sw_platform/?format=json")
        .then((response) => (this.software_platforms = response.data));
    },
    loadHardwarePlatforms() {
      this.$axios
        .get(process.env.VUE_APP_PROJECT_REQUEST_HOST + "/api/base/hw_platform/?format=json")
        .then((response) => (this.hardware_platforms = response.data));
    },
    loadRoles() {
      this.$axios
        // .get('http://127.0.0.1:8000/api/base/role/?format=json')
        .get(process.env.VUE_APP_PROJECT_REQUEST_HOST + "/api/base/role/?format=json")
        .then((response) => (this.roles = response.data.data));
    },
    loadEmployees() {
      this.$axios
        .get(process.env.VUE_APP_PROJECT_REQUEST_HOST + "/api/base/employee/?format=json")
        .then((response) => (this.employees = response.data.data));
    },
    loadCorporations() {
      this.$axios
        .get(process.env.VUE_APP_PROJECT_REQUEST_HOST + "/api/base/corporation/?format=json")
        .then(
          (response) =>
            (this.corporations = response.data.data.map((x) => {
              x.pinyin = pinyin(x.name, {
                style: pinyin.STYLE_NORMAL,
              }).join("");
              x.value = x.name;
              return x;
            }))
        );
    },
    loadDepartments() {
      this.$axios
        .get(process.env.VUE_APP_PROJECT_REQUEST_HOST + "/api/base/department/?format=json")
        .then(
          (response) =>
            (this.departments = response.data.data.map((x) => {
              x.pinyin = pinyin(x.name, {
                style: pinyin.STYLE_NORMAL,
              }).join("");
              x.value = x.name;
              return x;
            }))
        );
    },
    calculateDepreciation() {
      let depreciation = this.form.depreciation;
      let manmonthList = []; //人月
      let list = this.form.manPowerInput;
      var sum = [];
      //保存结果的数组
      var result = [];
      list.map((item) => {
        if (!item.total) {
          sum.push(item.input);
        }
      });
      for (var key in sum) {
        //遍历数组的每一项
        $.each(sum[key], function(index, val) {
          if (result[index] == null || result[index] == "") {
            result[index] = 0;
          }
          result[index] += parseFloat(val || 0);
        });
      }
      if (this.form.manPowerInput.length) {
        this.form.manPowerInput[
          this.form.manPowerInput.length - 1
        ].input = result;
        manmonthList = result;
      }
      let assets = [];
      let immaterial = [];
      this.form.assets.map((item2) => {
        this.estLabourWeek().map((v, i) => {
          assets[i] =
            parseFloat(item2.input[i] || 0) + parseFloat(assets[i] || 0);
        });
      });
      this.form.immaterial.map((item3) => {
        this.estLabourWeek().map((v, i) => {
          immaterial[i] =
            parseFloat(item3.input[i] || 0) + parseFloat(immaterial[i] || 0);
        });
      });
      this.estLabourWeek().map((v, i) => {
        depreciation.map((item4, i4) => {
          if (item4.field == "rent") {
            item4.input[i] =
              parseFloat(this.form.constants.depreciation_rent || 0) *
              parseFloat(manmonthList[i] || 0);
          }
          if (item4.field == "computer") {
            item4.input[i] =
              (parseFloat(this.form.constants.depreciation_computer || 0) *
                parseFloat(manmonthList[i] || 0)) /
              36;
          }
          if (item4.field == "renovation") {
            item4.input[i] =
              parseFloat(this.form.constants.depreciation_renovation || 0) *
              parseFloat(manmonthList[i] || 0);
          }
          if (item4.field == "house") {
            item4.input[i] =
              parseFloat(this.form.constants.depreciation_house || 0) *
              parseFloat(manmonthList[i] || 0);
          }
          if (item4.field == "fixed_assets") {
            item4.input[i] =
              parseFloat(assets[i] / 36) + parseFloat(item4.input[i - 1] || 0);
          }
          if (item4.field == "intangible_assets") {
            item4.input[i] =
              parseFloat(immaterial[i] / 24) +
              parseFloat(item4.input[i - 1] || 0);
          }
          this.$set(this.form.depreciation, i4, depreciation[i4]);
        });
      });
      this.calculateTotalCost();
      this.profit = this.estIncome * this.form.currency - this.estCost;
      if (this.estCost) {
        this.profit_rate =
          ((this.estIncome * this.form.currency - this.estCost) * 100) /
          this.estIncome;
      }
      if (this.totalManMonth && this.totalManMonth != 0) {
        this.avgCostRMB = this.estCost / this.totalManMonth;
      }
    }
  },
};
</script>
<style lang="scss" scoped>
/deep/ .el-input.is-readonly {
  background-color: #f5f7fa;
  border-color: #dfe4ed;
  color: #ff6363;
  cursor: not-allowed;
}
/deep/ .el-table .cell {
  white-space: pre-line;
}
/deep/ .el-table td.cell-grey {
  background-color:#909399 !important;
  color: #fff;
}
/deep/ .el-table td.cell-red {
  background-color:#ff4949 !important;
  color: #fff;
}
/deep/ .el-table td.cell-yellow {
  background-color:#ffba00 !important;
  color: #fff;
}
/deep/ .el-table td.cell-green {
  background-color:#13ce66 !important;
  color: #fff;
}
/deep/.el-table__body-wrapper{
    z-index: 2
}
.form-box {
    min-height: 200px;
}
.form-btn {
    text-align: right;
}
.btnColorL{
  color: #fff;
  background-color: #1890ff;
  border-color: #1890ff;
}
.btnColorN{
  color: #fff;
  background-color: #8cc8ff;
  border-color: #8cc8ff;
}
.tip {
  float: right;
  line-height: 36px;
  font-size: 14px;
  color: #6f6f6f;
}
.box-card {
  margin-bottom: 20px;
}
.border {
  box-sizing: content-box;
  height: 0;
  overflow: visible;
  margin-top: 1rem;
  margin-bottom: 1rem;
  border: 0;
  border-top: 1px solid rgba(0, 0, 0, .1);
}
.primary {
  color: #409EFF;
  font-size: 30px;
  font-weight: 400;
}
.table-form {
  margin-bottom: 0;
}
.table-form /deep/ .el-form-item__error {
  position: relative;
}
.form {
  margin-bottom: 180px;
}
.inline-input {
  width: 100%;
}
.request-submit {
  //width: 1140px;
  position: fixed;
  z-index: 998;
  padding: 15px 25px 15px 200px;
  bottom: 36px;
  height: 120px;
  border-top: 1px solid #dbe3e4;
  background-color: #fff;
  box-shadow: 0 -4px 4px -2px #e4e9f8;
  left: 54px;
  right: 0;
}
.el-select .el-input {
  width: 110px;
}
.input-with-select .el-input-group__prepend {
  background-color: #fff;
}
.label-item {
  margin-bottom: 8px;
  display: block;
}
.label-item:first-child {
  margin-bottom: 8px;
  display: block;
}
.label-item .label {
  width: 180px;
  text-align: right;
  display: inline-block;
  margin-right: 15px;
  color: #666;
}
.label-item .detail {
  display: inline-block;
}
.operations {
  display: inline-block;
  text-align: right;
  width: 8%;
}
.input-platform {
  margin-right: 15px;
}
.cost-about {
  display: inline-block;
  width: 30%;
  vertical-align: top;
  border-left: 1px solid #ddd;
  padding-right: 10px;
  box-sizing: border-box;
}
.cost-about:first-child {
  display: inline-block;
  width: 30%;
  border: none;
  vertical-align: top;
  padding-right: 10px;
  box-sizing: border-box;
}
.cost-about .cost-price .price {
  font-size: 18px;
  font-weight: 700;
  color: #ed711f;
}
.project-request-container {
  //min-width: 1140px;
  margin: 45px;
}
h3.project-title {
  color: rgb(31, 47, 61);
  font-weight: 400;
  font-size: 22px;
}
.btn-add {
  margin-bottom: 15px;
}
.btn-all {
  margin-bottom: 15px;
  float: right;
}
.el-row {
  // margin-bottom: 20px;
}
.el-col {
  border-radius: 4px;
}
.grid-content {
  border-radius: 4px;
  min-height: 36px;
}
.row-bg {
  padding: 10px 0;
}
</style>
